<?php
function no_cache()
{
    // Date in the past
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    // always modified
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    // HTTP/1.1
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    // HTTP/1.0
    header("Pragma: no-cache");
}
function write_log($mesaj)
{
    $filename = date("Ymd");
    $content = "data: " . date("d-M-Y");
    $content .= "  la ora " . date("H:i");
    $content .= "   ip: " . $_SERVER['REMOTE_ADDR'] . "   $mesaj\n";
    $content .= "-----------------------------------\n";
    $handle = fopen("$_SERVER[DOCUMENT_ROOT]" . "/error_log/" . "$filename", "a");
    fwrite($handle, $content);
    fclose($handle);
}
function write_mysql_log($nume, $op, $last_query, $id_connect)
{
    $str1 = "SELECT cr_ramas,cr_total,cr_consumat FROM clienti WHERE nume='$nume'";
    $result1 = mysql_query($str1, $id_connect);
    $value1 = mysql_fetch_assoc($result1);
    $cont = "T:" . $value1['cr_total'] . " R:" . $value1['cr_ramas'] . " C:" . $value1['cr_consumat'];
    $mesaj = $nume . ": " . $op . ": " . $last_query . " sit. cont " . $cont;
    $filename = "mysql " . date("Ymd");
    $content = "data: " . date("d-M-Y");
    $content .= "  la ora " . date("H:i");
    $content .= "   ip: " . $_SERVER['REMOTE_ADDR'] . "   $mesaj\n";
    $content .= "-----------------------------------\n";
    $handle = fopen("$_SERVER[DOCUMENT_ROOT]" . "/error_log/" . "$filename", "a");
    fwrite($handle, $content);
    fclose($handle);
    return $value1;
}
function random_str($length)
{
    $charset = "abcdefghijklmnopqrstuvwxyz";
    $charset .= "0123456789";
    $key = "";
    for ($i = 0; $i < $length; $i++)
        $key .= $charset[(mt_rand(0, (strlen($charset) - 1)))];
    return $key;
}
function build_xml_packet($message_id, $continut, $num_result = 0)
{
    //$str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?\>\r\n";
    $str .= "<datapacket mess_id=\"$message_id\" flag=\"1\" num_results=\"$num_result\">";
    $str .= $continut;
    $str .= "</datapacket>";
    echo $str;
    exit();
}
function build_xml_packet2($continut, $mess_id = 9, $flag = 1)
{
    //$str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?\>\r\n";
    $str .= "<?xml version='1.0' encoding='ISO-8859-1' ?>";
    $str .= "<rows flag=\"$flag\" messid=\"$mess_id\">";
    $str .= $continut;
    $str .= "</rows>";
    print $str;
    exit();
}
function send_error_xml($message_id)
{
    //header("Content-type: text/xml");
    //$str = "\<?xml version=\"1.0\" encoding=\"UTF-8\" \?\>";
    $str .= "<datapacket mess_id=\"$message_id\" flag=\"0\">";
    $str .= "</datapacket>";
    echo $str;
    exit();
}
function send_error2($message_id = 0, $rpc = "", $withExit = true)
{
    //header("Content-type: text/xml");
    $str .= "<?xml version='1.0' encoding='ISO-8859-1' ?>";
    $str .= "<rows messid=\"$message_id\" flag=\"0\" rpc=\"$rpc\" >";
    $str .= "<row name=\"error\" />";
    $str .= "</rows>";
    print $str;
    if ($withExit) {
        exit();
    }
}
function send_confirmation($message_id = 9)
{
    $str .= "<?xml version='1.0' encoding='ISO-8859-1' ?>";
    $str .= "<rows messid=\"$message_id\" flag=\"1\">";
    $str .= "<row name=\"succes\" />";
    $str .= "</rows>";
    print $str;
    exit();
}
function send_error($message_id)
{
    echo "&mess_id=$message_id&flag=0&";
    exit();
}
function get_logo($phone_icons, $icon)
{
    foreach ($phone_icons as $key => $value) {
        if ($key == $icon) {
            return $value;
        }
    }
    return "default_logo";
}
function success()
{
    $str .= "<datapacket flag=\"1\">";
    $str .= "</datapacket>";
    echo $str;
    exit();
}
function checkEmail($email)
{
    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",
        $email)) {
        return false;
    }
    return true;
}
function check_numar($numar)
{
    if (strlen($numar) < 6) {
        if (preg_match("/^([0-9-]+)$/", $numar)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
function send_mail_to_admin($imei, $nume, $marca, $model, $compania, $spec_code =
    'nu este cazul')
{
    $mail_to = "codigo@imeiserver.es";
    $subject = "Imei nou: " . $imei . " de " . $model;
    $data_in = date("d-M-Y  H:i", time());
    $headers = "From: codigo@imeiserver.es \r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1 ";
    $headers .= "MIME-Version: 1.0 ";
    $message = "\r\n\r\nExista un nou imei introdus in baza de date introdus la $data_in <br>";
    $message .= "Imei: " . $imei . "<br>";
    $message .= "Code special: " . $spec_code . "<br>";
    $message .= "Marca: " . $marca . "<br>";
    $message .= "Model: " . $model . "<br>";
    $message .= "Compania: " . $compania;
    mail($mail_to, $subject, $message, $headers);
}
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attach = false)
{
    $eol = "\n";
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    $headers .= "From: " . $fromname . "<" . $fromaddress . ">" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed;" . $eol . " boundary=\"{$mime_boundary}\"";
    ;

    $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" .
        "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n" . $body . "\n\n";

    if ($attach != false) {
        //atachament
        $fileatt = $attach['file']; // Path to the file
        $fileatt_type = "application/octet-stream"; // File Type
        $fileatt_name = substr($attach['file'], (strrpos($attach['file'], "/") + 1));
        ;
        if (($file = fopen($fileatt, 'rb')) === false) {
            die('Failed to open file!');
        }
        $data = fread($file, filesize($fileatt));
        fclose($file);

        $data = chunk_split(base64_encode($data));

        $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
            " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" .
            //" filename=\"{$fileatt_name}\"\n" .
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}\n";
    }
    $mail_sent = mail($to, $subject, $email_message, $headers);
    return $mail_sent;
}
function logged($tip)
{
    global $id_connect;
    if (isset($_POST['sesiune'])) {
        $sesiune = mysql_real_escape_string($_POST['sesiune']);
        if($sesiune == ''){
			return false;
		}
        $str = "SELECT tip_cont FROM clienti WHERE sesiune = '$sesiune'";
        $result = mysql_query($str, $id_connect);
        if (!$result) {
            send_error(mysql_error());
        }
        $num_rows = mysql_num_rows($result);
        if ($num_rows == 1) {
            $value = mysql_fetch_assoc($result);
            $tip_cont = $value['tip_cont'];
            if ($tip_cont == $tip) {
                return true;
            } else {
                write_log("user access notauthorized area identified by $user and pass:$pass");
                return false;
            }
        } else {
            write_log("access denying for user identified by $user and pass:$pass");
            return false;
        }
    } else {
        write_log("not session present!!!");
        return false;
    }
}
//MySQL functions
function connect_to_database($my_HOST, $my_USER, $my_PASS, $my_NAME)
{
    //connection to the MySql server
    $id_connect = @mysql_connect($my_HOST, $my_USER, $my_PASS);
    if (!$id_connect) {
        send_error(1);
        //die("Unable to connect to database ".$my_HOST.".!!! \n");
    }
    $db_select = @mysql_select_db($my_NAME, $id_connect);
    if (!$db_select) {
        send_error(1);
        //die("Unable to select the database ".$my_NAME.".!!! \n");
    }
    return $id_connect;
}
//mail functii, provin din BBPHP forum
function server_parse($socket, $response)
{
    $server_response = '';
    while (substr($server_response, 3, 1) != ' ') {
        if (!($server_response = fgets($socket, 256))) {
            echo "&raspuns=Couldn't get mail server response codes&";
            exit();
        }
    }
    if (!(substr($server_response, 0, 3) == $response)) {
        echo "&raspuns=Ran into problems sending Mail. Response: $server_response&";
        exit();
    }
}
//function pentru send mail
function smtpmail($mail_to, $subject, $message, $smtp_username, $smtp_password,
    $admin_email)
{
    global $smtp_host;
    //
    // Fix any bare linefeeds in the message to make it RFC821 Compliant.
    //
    //$message = preg_replace("/(?<!\r)\n/si", "\r\n", $message);
    if (trim($mail_to) == "") {
        exit();
    }
    if (trim($subject) == "") {
        die("No email Subject specified");
    }
    $mail_to_array = explode(",", $mail_to);
    //
    // Ok we have error checked as much as we can to this point let's get on
    // it already.
    //
    if (!$socket = fsockopen($smtp_host, 25, $errno, $errstr, 20)) {
        die("Could not connect to smtp host : $errno : $errstr");
    }
    server_parse($socket, "220");
    if (isset($smtp_username) && isset($smtp_password)) {
        // Send the RFC2554 specified EHLO.
        // This improved as provided by SirSir to accomodate
        // both SMTP AND ESMTP capable servers
        fputs($socket, "EHLO " . $smtp_host . "\r\n");
        server_parse($socket, "250");
        fputs($socket, "AUTH LOGIN\r\n");
        server_parse($socket, "334");
        fputs($socket, base64_encode($smtp_username) . "\r\n");
        server_parse($socket, "334");
        fputs($socket, base64_encode($smtp_password) . "\r\n");
        server_parse($socket, "235");
    } else {
        echo "ramura de jos";
        // Send the RFC821 specified HELO.
        fputs($socket, "HELO " . $smtp_host . "\r\n");
        server_parse($socket, "250");
    }
    // From this point onward most server response codes should be 250
    // Specify who the mail is from....
    fputs($socket, "MAIL FROM: <" . $admin_email . ">\r\n");
    server_parse($socket, "250");
    // Specify each user to send to and build to header.
    $to_header = "To: ";
    @reset($mail_to_array);
    while (list(, $mail_to_address) = each($mail_to_array)) {
        //
        // Add an additional bit of error checking to the To field.
        //
        $mail_to_address = trim($mail_to_address);
        if (preg_match('/[^ ]+\@[^ ]+/', $mail_to_address)) {
            fputs($socket, "RCPT TO: <$mail_to_address>\r\n");
            server_parse($socket, "250");
        }
        $to_header .= "<$mail_to_address>, ";
    }
    // Ok now we tell the server we are ready to start sending data
    fputs($socket, "DATA\r\n");
    // This is the last response code we look for until the end of the message.
    server_parse($socket, "354");
    // Send the Subject Line...
    fputs($socket, "Subject: $subject\r\n");
    // Now the To Header.
    fputs($socket, "$to_header\r\n");
    // Now any custom headers....
    //fputs($socket, "$headers\r\n\r\n");
    // Ok now we are ready for the message...
    fputs($socket, "$message\r\n");
    // Ok the all the ingredients are mixed in let's cook this puppy...
    fputs($socket, ".\r\n");
    server_parse($socket, "250");
    // Now tell the server we are done and close the socket...
    fputs($socket, "QUIT\r\n");
    fclose($socket);
    return true;
}
?>
